<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意：只允许为三级分类设置相关联参数"
        type="warning"
        show-icon
        :closable='false'>
      </el-alert>
      <el-row>
        选择商品分类：
        <el-cascader
          v-model="selectIndex"
          :options="options"
          :props="props"
          @change="handleChange">
        </el-cascader>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-button class='add-button' size='mini' type="primary" :disabled='!isSelect' @click='showAddDialog'>添加参数</el-button>
          </el-row>
          <el-table style="width: 100%" border :data='categoriesData' >
            <el-table-column type='expand'>
              <template #default='scope'>
                <el-tag :key="i.cat_id" v-for="i in scope.row.attr_vals" closable :disable-transitions="false" @close='clear(i.attr_name, scope.row)'>
                  {{i}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @blur="handleInputConfirm(scope.row)"
                  @keyup.enter.native="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label='#' type='index'></el-table-column>
            <el-table-column label='参数名称' prop='attr_name'></el-table-column>
            <el-table-column label='操作' >
              <template #default='scope'>
                <el-button type="primary" size='mini' icon="el-icon-edit" @click='showEditAttr(scope.row)'>编辑</el-button>
                <el-button type="danger" size='mini' icon="el-icon-delete" @click='deleteAttr(scope.row.attr_id)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-button class='add-button' size='mini' type="primary" :disabled='!isSelect' @click='showAddDialog'>添加属性</el-button>
          </el-row>
          <el-table style="width: 100%" border :data='categoriesData' >
            <el-table-column type='expand'>
              <template #default='scope'>
                <el-tag :key="i.cat_id" v-for="i in scope.row.attr_vals" closable :disable-transitions="false" @close='clear(i.attr_name, scope.row)'>
                  {{i}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @blur="handleInputConfirm(scope.row)"
                  @keyup.enter.native="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label='#' type='index'></el-table-column>
            <el-table-column label='参数名称' prop='attr_name'></el-table-column>
            <el-table-column label='操作' >
              <template #default='scope'>
                <el-button type="primary" size='mini' icon="el-icon-edit" @click='showEditAttr(scope.row)'>编辑</el-button>
                <el-button type="danger" size='mini' icon="el-icon-delete" @click='deleteAttr(scope.row.attr_id)'>删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="'添加' + DialogText"
      :visible.sync="addDialogVisi"
      width="50%"
      :before-close="handleClose">
      <el-form :model="FormData" :rules="FormData_rules" ref="FormData_ref" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="DialogText" prop="attr_name">
          <el-input v-model="FormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisi = false">取 消</el-button>
        <el-button type="primary" @click='addAttr'>确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'添加' + DialogText"
      :visible.sync="editDialogVisi"
      width="50%"
      :before-close="handleClose">
      <el-form :model="FormData" :rules="FormData_rules" ref="editFormData_ref" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="DialogText" prop="attr_name">
          <el-input v-model="FormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisi = false">取 消</el-button>
        <el-button type="primary" @click='editAttr'>确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectIndex:[],
      activeName:'many',
      options:[],
      props:{
        expandTrigger: 'hover',
        children:'children',
        label:'cat_name',
        value:'cat_id'
      },
      categoriesData:[],
      addDialogVisi: false,
      editDialogVisi: false,
      FormData: {
        attr_name:''
      },
      FormData_rules:{
        attr_name: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ],
      }
    }
  },
  computed: {
    isSelect() {
      if( this.selectIndex.length === 3 ) return true
      return false
    },
    DialogText() {
      if( this.activeName === 'many' ) return '动态参数'
      return '静态属性'
    }
  },
  methods: {
    async getCategories() {
      let res = await this.axios.get('categories')
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.options = res.data
    },
    async handleChange() {
      if( this.selectIndex.length !== 3 ){
        this.categoriesData = []
        return this.selectIndex = []
      } 
      this.activeName = 'many'
      this.getManyOnlyData()

    },
    async getManyOnlyData() {
      let res = await this.axios.get(`categories/${ this.selectIndex[2] }/attributes`, { params: { sel:this.activeName }} )
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      res.data.forEach( item => {
        item.attr_vals = item.attr_vals !== '' ? item.attr_vals.split(',') : []
        item.inputValue = ''
        item.inputVisible = false
      })
      this.categoriesData = res.data
    },
    handleClick() {
      if( this.selectIndex.length !== 3 ) return 
      this.getManyOnlyData()
    },
    handleInputConfirm( row ) {
      if( row.inputValue.trim().length == 0 ) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      this.submitArrt(row)
      row.inputValue = ''
      row.inputVisible = false
    },
    async submitArrt(row) { 
      let res = await this.axios.put(`categories/${ this.selectIndex[2] }/attributes/${ row.attr_id }`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if( res.meta.status == 200 ){
        this.pop.success(res.meta.msg)
      } else {
        this.pop.error(res.meta.msg)
      }
    },
    showInput( row ) {
      row.inputVisible = true
      this.$nextTick( ()=>{
        this.$refs.saveTagInput.focus()
      })
    },
    clear( id , row ) {
      row.attr_vals.splice(id,1)
      this.submitArrt(row)
    },
    async showAddDialog() {
      this.addDialogVisi = true
    }, 
    handleClose() {
      this.FormData = {
        attr_name:''
      }
      this.addDialogVisi ? this.$refs.FormData_ref.resetFields() : ''
      this.editDialogVisi ? this.$refs.editFormData_ref.resetFields() : ''
      this.addDialogVisi = false
      this.editDialogVisi = false
    },
    async addAttr() {
      let rel = await this.$refs.FormData_ref.validate().catch()
      if( !rel ) return this.pop.error('请填写内容')
      let res = await this.axios.post(`categories/${ this.selectIndex[2] }/attributes`, {
        attr_name: this.FormData.attr_name,
        attr_sel : this.activeName,
      })
      if( res.meta.status !== 201 ) return this.pop.error( res.meta.msg )
      this.getManyOnlyData()
      this.pop.success( res.meta.msg )
      this.$refs.FormData_ref.resetFields()
      this.addDialogVisi = false
    },
    showEditAttr( row ) {
      this.FormData = row
      this.editDialogVisi = true
    },
    async editAttr( ) {
      let rel = await this.$refs.editFormData_ref.validate().catch()
      if( !rel ) return this.pop.error('请填写内容')
      let res = await this.axios.put(`categories/${ this.selectIndex[2] }/attributes/${ this.FormData.attr_id }`, this.FormData)
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.getManyOnlyData()
      this.pop.success( res.meta.msg )
      this.$refs.editFormData_ref.resetFields()
      this.editDialogVisi = false
    },
    async deleteAttr(id) {
      let rel = await this.confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if( rel !== 'confirm' ) return this.pop('取消删除')
      let res = await this.axios.delete(`categories/${ this.selectIndex[2] }/attributes/${ id }`)
      if( res.meta.status !== 200 ) return this.pop.error( res.meta.msg )
      this.pop.success( res.meta.msg )
      this.getManyOnlyData()
    }
  },
  created() {
    this.getCategories()
  }
}
</script>

<style scoped>
.el-tag {
  margin:5px;
}
</style>